<template>
  <div class="">
    <el-card v-if="contentView">
      <el-row>
        <el-col :span="4" style="margin-right: 10px">
          <el-input
            placeholder="物料编号" size="medium"
            v-model="queryInfo.materialNumber"
            clearable>
          </el-input>

        </el-col>
        <el-col :span="4" style="margin-right: 10px">
          <el-input size="medium"
                    placeholder="物料描述"
                    v-model="queryInfo.materialName"
                    clearable>
          </el-input>
        </el-col>
        <el-col :span="4" style="margin-right: 10px">
          <el-input size="medium"
                    placeholder="需求计划单号"
                    v-model="queryInfo.planNumber"
                    clearable>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss"
                          v-model="queryInfo.receiveTimeStart" size="medium"
                          type="datetime"
                          placeholder="选择到货开始日期">
          </el-date-picker>
        </el-col>
        <el-col :span="4">
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss"
                          v-model="queryInfo.receiveTimeEnd" size="medium"
                          type="datetime"
                          placeholder="选择到货结束日期">
          </el-date-picker>
        </el-col>


        <el-col :span="2">
          <el-button   type="primary" icon="el-icon-search" @click="seacher">搜索</el-button>
        </el-col>


        <el-col :span="2" style="margin-top: 10px">
          <el-button size="mini" type="primary" icon="el-icon-download" @click="downloadTemplate">下载导入模板</el-button>
        </el-col>
        <el-col :span="2" style="margin-top: 10px">
          <el-button  size="mini"  type="primary" icon="el-icon-download" @click="addImoprt">新增导入</el-button>
        </el-col>

        <el-col :span="2" style="margin-top: 10px">
          <el-button  size="mini"  type="primary" icon="el-icon-download" @click="lookeDetails">查看数据</el-button>
        </el-col>
        <el-col :span="2" style="margin-top: 10px">
          <el-button  size="mini"  type="primary" icon="el-icon-download" @click="exportWarehousingF">导出数据</el-button>
        </el-col>


        <el-col :span="12" style="text-align: right;">
          <div>
            <!-- <el-button type="primary" icon="el-icon-upload2">导入</el-button> -->
<!--            <el-button v-if="authFilter('edit_procurement')" type="primary" icon="el-icon-plus" @click="operationView(0)">添加</el-button>-->
          </div>
        </el-col>
      </el-row>
      <!--表格-->
      <el-table  :row-style="{height: '10px'}" :cell-style="{padding:'0px'}"  :data="tableData" border v-loading="loading" >
<!--        &lt;!&ndash; 展开列 &ndash;&gt;-->
<!--        <el-table-column type="expand">-->
<!--          <template slot-scope="props">-->
<!--            <div>-->
<!--              <el-table-->
<!--                  :data="props.row.children"-->
<!--                  style="width: 100%"-->
<!--                  :header-cell-style="{ background: '#FAFAFA' }"-->
<!--                >-->
<!--                  <el-table-column label="物料名称" prop="materailName"></el-table-column>-->
<!--                  <el-table-column label="物料编号" prop="materailNumber"></el-table-column>-->
<!--                  <el-table-column label="实际数量" prop="actualQut"></el-table-column>-->
<!--                  <el-table-column label="计划数量" prop="planQut"></el-table-column>-->
<!--                  <el-table-column label="工厂非限制库存" prop="notLimitStock"></el-table-column>-->
<!--                </el-table>-->
<!--            </div>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="inTime" label="到货时间" align="center" :show-overflow-tooltip="true" width="100">
        </el-table-column>
        <el-table-column prop="planNumber" label="需求计划单号"  align="center" :show-overflow-tooltip="true" width="100">
        </el-table-column>
        <el-table-column prop="standObjectNumber" label="标准对象号"  align="center" :show-overflow-tooltip="true" width="100">
        </el-table-column>
        <el-table-column prop="orderNo" label="订单号" :show-overflow-tooltip="true" align="center" width="100">
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="物料编码" prop="materailNumber" align="center" width="100" :show-overflow-tooltip="true" ></el-table-column>
        <el-table-column label="物料描述" prop="materailName" align="center" width="100" :show-overflow-tooltip="true" ></el-table-column>
        <el-table-column label="数量" prop="qut" align="center" width="80"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="单位" prop="unit" align="center" width="70"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="repositoryName" label="库存地" align="center" width="100"  :show-overflow-tooltip="true"></el-table-column>
<!--        <el-table-column type="index" label="序号" v-if="false" align="center" width="55">-->
<!--        </el-table-column>-->
        <!--<el-table-column prop="repositoryName" label="仓库名称" align="center">-->
        <!--</el-table-column>-->

        <el-table-column prop="projectText" :show-overflow-tooltip="true" label="项目文本" align="center" width="100" >
        </el-table-column>
        <el-table-column prop="unloadingAddress" :show-overflow-tooltip="true" label="卸货点" align="center" width="100"></el-table-column>
        <el-table-column prop="submitText" label="提报单元" :show-overflow-tooltip="true" align="center" width="100"></el-table-column>

        <el-table-column prop="workOrderNo" label="工单/网络号" align="center" width="100"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="businessType" label="业务类型" align="center" width="100"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="singlePrice" label="单价" align="center" width="70"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="amount" label="金额" align="center" width="80"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="creatorName" label="提交人" align="center" width="100" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column  label="审核状态" align="center" width="100">
          <template slot-scope="scope">
            <span @click="history(scope.row)" v-if="scope.row.status.code==3" style="color: #1c9913;">{{scope.row.status.name}}</span>
             <span @click="history(scope.row)" v-else-if="scope.row.status.code==2" style="color: #ffb547;">{{scope.row.status.name}}</span>
             <span v-else style="color: #ff4141">{{scope.row.status.name}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column  label="操作" align="center" >-->
<!--        	<template  slot-scope="scope">-->
<!--        		<div   >-->
<!--              <el-button type="text" icon="el-icon-tickets" @click="operationView(1,scope.row)">编辑</el-button>-->
<!--              <el-button v-if="scope.row.status.code == 2" type="text" icon="el-icon-edit" @click="withdraw(scope.row)">撤回</el-button>-->
<!--        		</div>-->
<!--        	</template>-->
<!--        </el-table-column>-->
      </el-table>
      <div style="float: right">合计金额:{{sum}}</div>
      <el-pagination style="text-align: center;" :disabled="loading" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNo" :page-sizes="[25,50]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
      <submitForm v-if="!contentView" :subData="subData" @closeView="closeView" @refresh="refreshTable"></submitForm>
      <historyLook :visible.sync="visible" :historyTables="historyTables"/>

    <el-dialog :visible.sync="importVisible" append-to-body width="30%">
      <p style="text-align: center;" class="map">新增导入</p>
      <el-form :model="importForm">
        <el-form-item label="导入的文件" prop="fileName">
          <el-upload   style="margin: 0 10px;" :action="importUrl+'import/uploadExcel'"
                       :on-success="uploadSuccessHandler"
                       :on-error="uploadFailHandler"
                       :before-upload="beforeUpload"
                       :file-list="fileList"
                       multiple
                       name="excel" :show-file-list="true" :headers="headers">
            <el-button  type="primary" icon="el-icon-download">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">上传EXCEL文件</div>
          </el-upload>

        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button class="global-button" round type="primary" @click="importVisible = false">关闭</el-button>
        <el-button class="global-button" round type="primary" @click="submitImport">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getHistoryLook,postWithdraw } from '@/api/user'
import { pageWarehousing, deleteWarehousing,getwlId,totalPageWarehousingAmount,exportWarehousing } from '@/api/materialScience/warehousingApplication.js'
import submitForm from './components/submitForm.vue'
import historyLook from '@/components/historyLook'
import { mapState } from "vuex";
import { applyImport,downloadTemplateByType } from '@/api/importApply.js'
let $this = null
export default {
  name: 'purchase',
  components: {
    submitForm,
    historyLook
  },
  computed: {
    ...mapState(["authList"]),
  },
  data () {
    return {
      contentView: true,
      placeholder: '材料名称',
      loading: false,
      queryInfo: {
        pageNo: 1,
        pageSize: 25,
      },
      tableData: [],
      total: 0,
      subData: {
        btnId: 0,
        id: ''
      },
      visible: false,
      historyTables: [],
      importVisible:false,
      importForm:{
        importType:3,
        fileName:''
      },
      fileList:[],
      importUrl:this.importUrl,
      headers: {
        apiKey: window.sessionStorage.getItem('token')
      },
      sum:0
    }
  },
  created () {
    $this = this
    if(this.$route.params.id) {
      this.contentView = false
      this.subData = {
        btnId: 1,
        id: this.$route.params.id
      }
    }
    //$this.getPageWarehousing()
  },
  methods: {
    exportWarehousingF(){

      exportWarehousing($this.queryInfo).then(res=>{
        $this.downloadFile(res,  '入库申请列表')
      })

    },
    downloadTemplate () {
      $this.isDown = true
      const ttt={
        type:3
      }
      downloadTemplateByType(ttt).then(res => {
        $this.isDown = false
        $this.downloadFile(res,  '入库申请导入模板')
      }).catch(err => {
        $this.isDown = false
        return $this.$message.error('导出文件错误')
      })
    },
    lookeDetails(){
      $this.getPageWarehousing()
    },
    addImoprt () {
      this.importVisible = true
    },
    submitImport(){
      if (!$this.importForm.fileName){
        $this.$message({
          type: 'error',
          message: '文件不能为空',
          showClose: true
        })
        return
      }
      $this.isDown = true
      applyImport($this.importForm).then(res => {

        if (res.headers['content-type']&&res.headers['content-type'].indexOf('multipart/form-data')>=0){
          $this.isDown = false
          $this.downloadFile(res,  '错误信息')
          this.importVisible = false
          return;
        }

        $this.isDown = false
        // console.log(res)
        if(res.headers['content-type']&&res.headers['content-type'].indexOf('application/json')>=0){
          $this.$message({
            type: 'error',
            message: '导入失败,请检查审批配置',
            showClose: true
          })
          return
        }
        $this.$message({
          type: 'success',
          message: '提交成功',
          showClose: true
        })
        this.importVisible = false
        $this.$emit('refresh')

      })
    },
    // 导入成功触发
    beforeUpload(file) {
      this.$loading({
        lock: true,
        text: '正在上传...',
        spinner: 'el-icon-loading',
      })
    },
    // 导入成功触发
    uploadSuccessHandler (response, file, fileList) {
      this.$loading().close()
      if (response.success) {
        $this.$message({
          type: 'success',
          message: '上传成功,请提交审批',
          showClose: true
        })
        $this.importForm.fileName=response.data.fileName
        $this.importForm.originFileName=response.data.originFileName
        $this.fileList=[]
        $this.fileList.push({name:response.data.originFileName,url:''})
        // this.getPageProcurement()
      } else {
        $this.$message({
          type: 'error',
          message: response.message,
          showClose: true
        })
        $this.fileList=[]
      }
    },
    uploadFailHandler () {
      this.$loading().close()
      $this.$message.error('上传失败')
    },
    downloadFile (res, name) {
      const blob = new Blob([res.data])
      const fileName = name + '.xlsx'
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    },
    expend (row,label) {
      if(label.length > 0) {
        getwlId(row.id).then(res => {
          row.children = res.data.data.slice(0)
          if (res.data.code != 200) {
            return $this.$message.error(res.data.message)
          }
        }).catch(err => {
        })
      }

    },
  authFilter (code) {
      let flag = false
      if(this.authList.length) {
        this.authList.forEach(item => {
          if(item.resourceCode == code) {
            flag = true
          }
        })
      }
      return flag
    },
    // 撤回
    withdraw (row) {
      this.$loading()
     postWithdraw({"documentId": row.id }).then(res => {
       this.$loading().close()
        const { data } = res
        if(data.code == "200") {
          this.getPageWarehousing()
          this.$message.success(data.message)
        }else {
          this.$message.error(data.message)
        }
      })
    },
    // 审批历史
    history (row) {
      getHistoryLook(row.processInstanceId).then(res => {

        this.historyTables = res.data.data
        this.visible = true
      })
    },
    getPageWarehousing () {
      $this.loading = true
      pageWarehousing($this.queryInfo).then(res => {
        $this.loading = false
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        res.data.data.records.map(item => {
            item.children = [];
        })
        $this.tableData = res.data.data.records
        $this.total = res.data.data.total

      }).catch(err => {
        $this.loading = false
        return $this.$message.error(err.message)
      })

      totalPageWarehousingAmount($this.queryInfo).then(res=>{
        $this.sum=res.data.data
      })
    },
    handleCurrentChange (val) {
      $this.queryInfo.pageNo = val
      $this.getPageWarehousing()
    },
    handleSizeChange (size) {
      $this.queryInfo.pageSize = size
      $this.getPageWarehousing()
    },
    seacher (key) {

      $this.getPageWarehousing()
    },
    operationView (btnId, row) {
      if (btnId === 0) {
        $this.subData.btnId = btnId
        $this.contentView = false
      } else if (btnId === 1) {
        $this.subData.btnId = btnId
        $this.subData.id = row.id
        $this.contentView = false
      } else if (btnId === 2) {
        $this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return $this.deleteWarehousing(row)
        }).catch(() => {
          return $this.$message.info('已取消删除')
        })
      } else {
        return $this.$message.error('操作错误')
      }
    },
    // 删除
    deleteWarehousing (row) {
      $this.$set(row, 'loading', true)
      deleteWarehousing(row.id).then(res => {
        $this.$set(row, 'loading', false)
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        $this.getPageWarehousing()
        return $this.$message.success('删除成功')
      }).catch(err => {
        $this.$set(row, 'loading', false)
        return $this.$message.error('操作错误')
      })
    },
    // 返回table
    closeView () {
      $this.contentView = true
    },
    refreshTable () {
      $this.contentView = true
      $this.getPageWarehousing()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
